package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.config.CacheService;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    /**
     * 添加任务
     * 有哪些参数:任务的执行时间、任务的执行参数、任务的类型、优先级
     * 返回值：任务的id
     *
     * @param task
     */
    @Override
    public Long addTask(Task task) {

        //1.添加任务到数据库中
        boolean success = addTaskToDB(task);

        if (success) {
            //2.添加任务到redis
            addTaskToCache(task);

        }
        return task.getTaskId();
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务到redis
     *
     * @param task
     */
    private void addTaskToCache(Task task) {

        //组装key
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取未来5分钟的时间点
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //2.1 如果任务的执行时间小于等于当前时间，存储redis中的list
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= calendar.getTimeInMillis()) {
            //2.2 如果任务的执行时间小于等于未来5分钟，存储redis中的zset
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }


    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库中
     *
     * @param task
     */
    private boolean addTaskToDB(Task task) {

        boolean flag = false;
        try {
            //保存任务到任务表
            Taskinfo taskinfo = new Taskinfo();
            //属性拷贝
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));

            taskinfoMapper.insert(taskinfo);

            //给task的id赋值
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            //属性拷贝
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            //设置verison,乐观锁
            taskinfoLogs.setVersion(1);
            //设置任务的状态
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);

            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (BeansException e) {
            throw new RuntimeException("TaskServiceImpl-保存任务失败");
        }

        return flag;
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {

        boolean flag = false;

        //修改数据库（删除任务，修改任务日志）
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);

        //删除redis相关数据
        if (task != null) {
            removeTaskToCache(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 删除redis相关数据
     *
     * @param task
     */
    private void removeTaskToCache(Task task) {

        //组装key
        String key = task.getTaskType() + "_" + task.getPriority();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //2.1 如果任务的执行时间小于等于当前时间，删除list数据
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            //2.2 如果任务的执行时间小于等于未来5分钟，删除的zset数据
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 修改数据库（删除任务，修改任务日志）
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(Long taskId, int status) {

        try {
            Task task = new Task();

            //删除任务
            taskinfoMapper.deleteById(taskId);

            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);

            //设置task对象
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            return task;
        } catch (BeansException e) {
            throw new RuntimeException("TaskServiceImpl-修改任务失败");
        }

    }

    /**
     * 消费任务
     *
     * @param taskType
     * @param priority
     * @return
     */
    @Override
    public Task poll(Integer taskType, Integer priority) {

        Task task = null;

        try {
            String key = taskType + "_" + priority;

            //从redis的list去pop数据
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)) {
                task = JSON.parseObject(task_json, Task.class);
                //修改数据库的操作（删除任务、修改任务日志）
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            throw new RuntimeException("taskServiceImpl-消费任务失败");
        }


        return task;
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){

        String token = cacheService.tryLock("TASK_SYNC_DATA", 1000 * 30);
        if(StringUtils.isNotBlank(token)){
            System.out.println("数据进行了同步"+new Date());

            //获取所有的future的key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {//future_100_50
                //获取对应的topic的key
                String topicKey = ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];
                //查询符合条件的数据（到期的数据）
                Set<String> values = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if(values != null && values.size() > 0){
                    //从zset中找到到期的数据，同步到list中  （redis管道流）
                    cacheService.refreshWithPipeline(futureKey,topicKey,values);
                    log.info("成功的将"+futureKey+"刷新到了"+topicKey);
                }
            }
        }

    }

    @PostConstruct  //初始化方法
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){

        //清理数据，数据的双写一致
        clear();


        //获取未来5分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);


        //查询符合条件的数据（查表，小于等于未来5分钟的数据）
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));
        if(taskinfoList != null && taskinfoList.size() > 0){
            for (Taskinfo taskinfo : taskinfoList) {
                //存储到redis
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }

    }

    /**
     * 清理redis中的数据
     */
    private void clear() {
        //获取所有的key
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }
}
